<?php

namespace User\Model;

use User\Model\Entity\User;
use Zend\Db\TableGateway\AbstractTableGateway;
use Zend\Db\Adapter\Adapter;
use Zend\Db\Sql\Select;

class UserModel extends AbstractTableGateway {
	protected $table = 'tb_user';

	public function __construct(Adapter $adapter) {
		$this->adapter = $adapter;
	}

	public function fetchAll() {
		$resultSet = $this->select();
		
		$users = array();
		foreach($resultSet as $set) {
			$users[] = new User((array) $set);
		}
		return $users;
	}
	
	public function saveUser(User $user) {
		$data = array(
            'email'			=> $user->getEmail(),
            'name'			=> $user->getName(),
            'gender'		=> $user->getGender(),
            'status'		=> true,
            'date_added'	=> date("Y-m-d H:i:s"),
		);
		
		if($user->getPassword()) {
			$data['password'] = $user->getPassword();
		}

		$id = (int) $user->getId();
		if(empty($id)) {
			$this->insert($data);
			$id = $this->getLastInsertValue();
		} else {
			if($this->getUser($id)) {
				$this->update($data, array('user_id' => $id));
			}
		}
	}
	
	public function changePassword(User $user) {
		$data = array(
            'password' => $user->getPassword(),
		);
		
		$id = (int) $user->getId();
		if($this->getUser($id)) {
			$this->update($data, array('user_id' => $id));
		}
	}
	
	public function getUser($id) {
		$resultSet = $this->select(function (Select $select) use ($id) {
			$select->where(array(
				'user_id' => $id,
			));
		});

		$rowSet = $resultSet->current();
		if(!$rowSet) {
			throw new \Exception("Could not find row " . $id);
		}

		return new User((array) $rowSet);
	}
	
	public function getUserBy(array $where) {
		$resultSet = $this->select(function (Select $select) use ($where) {
			$select->where($where);
		});

		$rowSet = $resultSet->current();
		if(!$rowSet) {
			throw new \Exception("Could not find row ");
		}

		return new User((array) $rowSet);
	}
	
	public function checkBy(array $where) {
		$resultSet = $this->select(function (Select $select) use ($where) {
			$select->where($where);
		});
		return (bool) $resultSet->current();
	}
}